/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-09-30 18:13:01
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-10-03 14:52:24
 * @FilePath: /GateServer/src/rpc/VarifyGrpcClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "varifygrpcclient.h"
#include <algorithm>
#include <cstddef>
#include <grpcpp/channel.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/impl/codegen/client_context.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/codegen/status_code_enum.h>
#include <grpcpp/security/credentials.h>
#include <memory>
#include <mutex>
#include <string>
#include "grpcpp/grpcpp.h"
#include "../util/util.h"
#include "../util/logger.h"
#include"../util/config.h"




static Yizhi::ConfigVar<std::string>::ptr g_host_value=Yizhi::ConfigMgr::Lookup("rpc.host",(std::string)"127.0.0.1","");
static Yizhi::ConfigVar<std::string>::ptr g_port_value=Yizhi::ConfigMgr::Lookup("rpc.port",(std::string)"50051");
VarifyGrpcClient::VarifyGrpcClient(){
   m_pool.reset(new RpcConnectionPool(g_host_value->getvalue(),g_port_value->getvalue(),5));
}

message::GetVarifyRsp VarifyGrpcClient::GetVarifyCode(std::string email){
    grpc::ClientContext context;
    message::GetVarifyReq request;
    message::GetVarifyRsp reply;
    request.set_email(email);
    auto stub=m_pool->GetConnection();

    grpc::Status status=stub->GetVarifyCode(&context,request,&reply);

    if(status.ok()){
        LOG_DEBUG("rpc service start");
        return reply;
        LOG_DEBUG("rpc service end");
    }
    else {
        reply.set_error(Yizhi::Ecode::RPCFLASE);
    }
    return reply;

}

RpcConnectionPool::RpcConnectionPool(std::string host, std::string port, size_t size=2)
    : m_pool_size(size)
    , m_host(host)
    , m_port(port) {

    for(size_t i = 0; i < size; i++) {  // 改为 size_t
        std::string taget=host+":"+port;
        std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(
            taget, 
            grpc::InsecureChannelCredentials()
        );
        
        // 可以添加简单的连接状态检查
        auto state = channel->GetState(true);
        // if (state != GRPC_CHANNEL_READY) {
        //     // 记录警告，但不阻止创建
        //     LOG_ERROR("Warning: Channel state error");
        // }
         
        m_connections.push(message::GetVarifyService::NewStub(channel));
    }
}   

RpcConnectionPool::~RpcConnectionPool(){
    close();  // 先关闭
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        while (!m_connections.empty()) {
            m_connections.pop();
        }
    }
}

std::unique_ptr<message::GetVarifyService::Stub> RpcConnectionPool::GetConnection(){
    std::unique_lock<std::mutex> lock(m_mutex);
    m_cond.wait(lock, [this]() {
        return !m_connections.empty() || m_stop.load();
    });
    
    // 关键修复：检查停止状态和队列是否为空
    if (m_stop.load() || m_connections.empty()) {
        return nullptr;
    }
    
    auto res = std::move(m_connections.front());
    m_connections.pop();
    return res;
}

void RpcConnectionPool::ReturnConnection(std::unique_ptr<message::GetVarifyService::Stub> res){
    std::lock_guard<std::mutex> lock(m_mutex);
    if(m_stop){
        return;  // 池已关闭，丢弃连接
    }
    m_connections.push(std::move(res));
    m_cond.notify_one();
}

void RpcConnectionPool::close(){
    m_stop = true;
    m_cond.notify_all();
}